import React, { Fragment, PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { DATA_ENTRY, AdvancedSearch, NoQueryC } from '../../../comps';
import DrawBoardC from './drawBoard';
import _ from 'lodash';

moment.locale('zh-cn');
@Form.create()
class RightContent extends PureComponent {
  state = {
    disabledDateRange: true, // 时间区间是否可选择
    productCode: undefined, // 产品code
    searchObj: undefined, // 查询条件，
    currentList: undefined, // 选中的模板
    portfolioName: undefined, // 产品名称
    defaultType: '2', // 默认2
    codeKey: null, // 产品key用于跳转匹配
  };

  componentDidMount() {
    this.props.onRef(this);
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.currentModuleList) != JSON.stringify(this.props.currentModuleList)) {
      // 模板设置改变选中项，面板也需要更新
      this.setState({
        currentList: nextProps.currentModuleList ? _.cloneDeep([...nextProps.currentModuleList]) : undefined,
      });
    }
    if (JSON.stringify(nextProps.productCode) != JSON.stringify(this.props.productCode)) {
      this.changeProduct(nextProps.productCode, 'code', nextProps.portfolioType); // barra工作台分析概览过来的，查询对应的时间范围
    }
    // 从主功能页面带初始条件跳转跳转进来
    if (JSON.stringify(nextProps.params) != JSON.stringify(this.props.params) && this.props.type == 'main') {
      const promise = this.changeProduct(nextProps.params.portfolioCode, 'code', undefined, nextProps.params.timeRange); // 查询对应的时间范围
      promise.then(() => {
        // 给产品赋值
        this.product?.props.form.setFieldsValue({
          product: `${nextProps.params.portfolioCode} - ${nextProps.params.portfolioName}`,
        });

        const arr = nextProps.moduleList?.filter((item) => item.isSystem == '1');
        const selectModule = arr && arr.length ? arr[0].value : undefined; /// /默认第一个系统模板
        if (!nextProps.moduleList?.length) {
          // 首次进入还没拿到模板列表
          const promise1 = this.getModuleList(); // 获取模板列表
          promise1.then((res) => {
            // 默认第一个系统模板
            const temp = res && res.length ? (res.filter((item) => item.isSystem == '1')?.length ? res.filter((item) => item.isSystem == '1')[0].value : undefined) : undefined;
            this.state.HOlDDATERANGEC?.props.form.setFieldsValue({ selectModule: temp });
            // 拿到所有表单的值
            const obj = this.state.HOlDDATERANGEC?.state.COMPLEXDATE.props.form.getFieldsValue();
            if (obj.beginDate && obj.endDate) {
              this.searchData({
                ...obj,
                selectModule: temp,
              });
            } else {
              this.setState({
                currentList: undefined,
              });
              // 没有时间区间 则不请求数据
            }
          });
        } else {
          // 有模板列表
          const obj = this.state.HOlDDATERANGEC?.state.COMPLEXDATE.props.form.getFieldsValue();
          this.state.HOlDDATERANGEC?.props.form.setFieldsValue({ selectModule });
          if (obj.beginDate && obj.endDate) {
            this.searchData({
              ...obj,
              selectModule,
            });
          } else {
            this.setState({
              currentList: undefined,
            });
            // 没有时间区间 则不请求数据
          }
        }
      });
    }
  }

  getModuleList = () => {
    // 获取模板列表
    const { dispatch } = this.props;
    const that = this;
    const p = new Promise(function (resolve, reject) {
      dispatch({
        type: 'profitOverviewM/getModuleList',
        payload: {
          type: that.props.type,
        },
        callback: (data) => {
          resolve(data);
        },
      });
    });
    return p;
  };

  // 产品改变 取code
  changeProduct = (e, type, portfolioType, timeRange) => {
    const func = new Promise((resolve, reject) => {
      if (e) {
        const productObj = e.info;

        this.setState(
          {
            defaultType: timeRange || this.state.defaultType, // 从用户视图跳转过来 就用那边带过来的 没有则为默认值2
            portfolioType,
            productCode: type == 'code' ? e : productObj.code,
            portfolioName: type == 'code' ? e : productObj.mame,
            codeKey: productObj && productObj.value,
          },
          () => {
            setTimeout(() => {
              resolve();
            }, 400);
          },
        );
      } else {
        this.setState(
          {
            portfolioType,
            productCode: '',
            portfolioName: '',
          },
          () => {
            setTimeout(() => {
              resolve();
            }, 400);
          },
        );
      }
    });
    return func;
  };

  // 点击查询按钮 遍历引入该模板对应的子组件  向子组件抛出对应查询条件 portfolioCode(产品code)、beginDate（开始时间）、endDate（结束时间）、timeRange
  searchData = (searchObj) => {
    const { moduleList } = this.props;
    const arr = ['beginDate', 'endDate', 'timeRange', 'product', 'selectModule'];
    const searchArr = this.props.type == 'barra' ? arr.filter((item) => item != 'product') : [...arr];
    for (let i = 0; i < searchArr.length; i++) {
      if (searchObj[searchArr[i]] === undefined) {
        message.warning('所有选项必填！');
        return;
      }
    }
    const { selectModule } = searchObj;
    const tempArr = moduleList.filter((item) => item.value == selectModule);
    const data = tempArr[0]?.moduleList; // 获取对应的模板数据
    this.props.moduleIdChange(searchObj.selectModule, new Date().getTime(), _.cloneDeep(data)); // 将选中模板名称id 传递给父组件
    if (this.props.portfolioType) {
      // barra
      searchObj.flag = this.props.flag;
      searchObj.indexCode = this.props.indexCode;
    }
    searchObj.portfolioCode = this.state.productCode;
    searchObj.portfolioName = this.state.portfolioName;
    searchObj.beginDate = moment(searchObj.beginDate).format('YYYY-MM-DD');
    searchObj.endDate = moment(searchObj.endDate).format('YYYY-MM-DD');
    // delete searchObj.selectModule;
    delete searchObj.product;

    this.setState({
      searchObj,
      currentList: _.cloneDeep(data),
    });
  };

  // 重置页面
  // reset = (type) => {//左侧菜单 增删改 都需要重置页面
  //   if (type == "part") {//只重置模板名称表单 其余不变
  //     this.state.searchRef.props.form.setFieldsValue({
  //       selectModule: undefined,
  //     })
  //     this.setState({
  //       currentList: undefined,//选中的模板
  //       searchObj: undefined,//查询条件，
  //     })
  //   } else {
  //     this.state.searchRef.handleReset();//重置查询组件
  //     this.setState({
  //       disabledDateRange: true,//时间区间是否可选择
  //       productCode: undefined,//产品code
  //       searchObj: undefined,//查询条件，
  //       currentList: undefined,//选中的模板
  //     })
  //   }
  // }
  // 刷新页面
  reset = () => {
    this.props.moduleIdChange(); // 将选中模板名称id 传递给父组件
    this.state.searchRef.handleReset(); // 重置查询组件
    this.setState({
      disabledDateRange: true, // 时间区间是否可选择
      productCode: undefined, // 产品code
      searchObj: undefined, // 查询条件，
      currentList: undefined, // 选中的模板
    });
  };

  render() {
    const { moduleList } = this.props;
    const { searchObj, currentList, defaultType, codeKey } = this.state;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'product',
          title: '产品名称',
          type: DATA_ENTRY.PRODUCTLIST,
          dataType: 2,
          isQueryDetail: false,
          onChange: (e) => this.changeProduct(e),
          tradeModel: ['BOOKKEEPING_MODE', 'COMMAND_MODE', 'VALUATION_BOOKKEEPING_MODEL'],
          hide: this.props.type != 'main',
          onRef: (ref) => (this.product = ref),
        },
        {
          selectIndex: 'timeRange',
          startIndex: 'beginDate',
          endIndex: 'endDate',
          title: '时间区间',
          type: DATA_ENTRY.HOlDDATERANGEC,
          productCode: this.state.productCode,
          barraArgs: this.state.portfolioType
            ? {
                portfolioType: this.state.portfolioType,
                flag: 2,
              }
            : undefined,
          onRef: (ref) => this.setState({ HOlDDATERANGEC: ref }),
          defaultType,
        },
        {
          dataIndex: 'selectModule',
          title: '模板名称',
          type: DATA_ENTRY.SELECT,
          dataSource: moduleList,
          initialValue: this.props.type === 'main' && 'db6d084927944eab84171f38fc9c550f',
        },
        {
          dataIndex: 'needPenetrate',
          title: '是否穿透',
          type: DATA_ENTRY.SELECT,
          isTrueFalseJudge: true,
          initialValue: '0',
          hide: this.props.type != 'main',
        },
      ],
      onRef: (ref) => this.setState({ searchRef: ref }),
      onQuery: (e) => {
        this.searchData(e);
      },
      onClear: () => {
        // 日期重置方法
        // this.state.HOlDDATERANGEC.setSelctAndDate("", "", "");
        this.props.moduleIdChange(); // 将选中模板名称id 传递给父组件
        this.setState({
          // 重置页面数据
          productCode: undefined,
          disabledDateRange: true,
          searchObj: undefined,
          currentList: undefined,
        });
      },
    };
    return (
      <Fragment>
        <AdvancedSearch {...searchProps} />
        {!currentList?.length ? <NoQueryC height={this.props.isFloatLeft ? '622px' : undefined} /> : null}
        {searchObj && currentList?.length ? (
          <DrawBoardC
            selectModule={searchObj.selectModule}
            type={this.props.type}
            treeData={this.props.treeData}
            drawingBoardID={'profitOVerview'}
            searchObj={searchObj}
            list={currentList}
            codeKey={codeKey}
          />
        ) : null}
      </Fragment>
    );
  }
}
export default connect(({ profitOverviewM, keyFiguresM }) => ({
  profitOverviewM,
  keyFiguresM,
}))(RightContent);
